package com.tjetc.controller;

import com.tjetc.controller.messages.CreateTaskRequest;
import com.tjetc.controller.messages.CreateTaskResponse;
import com.tjetc.controller.messages.OpenAiChatModel;
import com.tjetc.controller.messages.TaskStatusResponse;
import com.tjetc.entity.TravelPlans;
import com.tjetc.model.*;
import com.tjetc.service.TaskManager;
import com.tjetc.service.TravelPlansService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("ai")
@CrossOrigin
public class ChatController {

    @Resource
    private OpenAiChatModel chatModel;

    @Resource
    private TaskManager taskManager;

    @Resource
    private TravelPlansService travelPlansService;

    // 每个任务维护自己的聊天历史
    private final ConcurrentHashMap<String, List<Message>> taskChatHistories = new ConcurrentHashMap<>();

    // 创建AI生成任务
    @PostMapping(value = "/create-task", consumes = MediaType.APPLICATION_JSON_VALUE)
    public CreateTaskResponse createTask(@RequestBody CreateTaskRequest request) {
        // 创建新任务
        String taskId = taskManager.createTask();

        // 初始化该任务的聊天历史
        List<Message> chatHistory = new ArrayList<>();
        chatHistory.add(new UserMessage(request.getMessage()));
        taskChatHistories.put(taskId, chatHistory);

        // 提交任务到线程池异步处理
        taskManager.submitTask(taskId, () -> {
            try {
                List<Message> history = taskChatHistories.get(taskId);
                Prompt prompt = new Prompt(history);

                System.out.println("处理任务: " + taskId + ", 消息: " + request.getMessage());

                // 调用AI模型
                ChatResponse chatResponse = chatModel.call(prompt);

                // 处理响应
                if (chatResponse.getResult() != null && chatResponse.getResult().getOutput() != null) {
                    history.add(chatResponse.getResult().getOutput());

                    // 更新任务状态为完成
                    TaskManager.TaskInfo taskInfo = taskManager.getTaskInfo(taskId);
                    taskInfo.setStatus(TaskManager.TaskInfo.Status.COMPLETED);
                    taskInfo.setResult(chatResponse);

                    String responseContent = chatResponse.getResult().getOutput().getContent();
                    System.out.println("任务: " + taskId + " 完成, 响应: " +
                            (responseContent != null ? responseContent.substring(0, Math.min(50, responseContent.length())) + "..." : "无内容"));

                    // 保存到数据库
                    saveTravelPlanToDatabase(taskId, request.getMessage(), responseContent);

                } else {
                    // 处理错误情况
                    TaskManager.TaskInfo taskInfo = taskManager.getTaskInfo(taskId);
                    taskInfo.setStatus(TaskManager.TaskInfo.Status.FAILED);
                    taskInfo.setErrorMessage("AI模型返回空响应");
                    System.out.println("任务: " + taskId + " 失败: AI模型返回空响应");

                    // 保存失败记录到数据库
                    saveTravelPlanToDatabase(taskId, request.getMessage(), null, "failed");
                }
            } catch (Exception e) {
                e.printStackTrace();

                // 更新任务状态为失败
                TaskManager.TaskInfo taskInfo = taskManager.getTaskInfo(taskId);
                taskInfo.setStatus(TaskManager.TaskInfo.Status.FAILED);
                taskInfo.setErrorMessage("处理请求时发生错误: " + e.getMessage());
                System.out.println("任务: " + taskId + " 异常: " + e.getMessage());

                // 保存异常记录到数据库
                saveTravelPlanToDatabase(taskId, request.getMessage(), null, "failed");
            }
        });

        return new CreateTaskResponse(taskId);
    }

    // 检查任务状态
    @GetMapping("/check-task/{taskId}")
    public TaskStatusResponse checkTask(@PathVariable String taskId) {
        TaskStatusResponse response = new TaskStatusResponse();
        TaskManager.TaskInfo taskInfo = taskManager.getTaskInfo(taskId);

        if (taskInfo == null) {
            response.setStatus("not_found");
            response.setErrorMessage("任务不存在");
            return response;
        }

        // 转换内部状态为API响应
        switch (taskInfo.getStatus()) {
            case PENDING:
            case PROCESSING:
                response.setStatus("processing");
                break;
            case COMPLETED:
                response.setStatus("completed");
                response.setResult(taskInfo.getResult());
                break;
            case FAILED:
                response.setStatus("failed");
                response.setErrorMessage(taskInfo.getErrorMessage());
                break;
        }

        return response;
    }

    // 保留原来的直接API供简单请求使用
    @PostMapping(value = "/chat", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ChatResponse chatWithPost(@RequestBody ChatRequest chatRequest) {
        try {
            String message = chatRequest.getMessage();
            System.out.println("收到直接POST请求消息: " + message);

            // 为直接API请求创建临时taskId
            String tempTaskId = "direct-" + java.util.UUID.randomUUID().toString();

            List<Message> chatHistory = new ArrayList<>();
            chatHistory.add(new UserMessage(message));

            Prompt prompt = new Prompt(chatHistory);
            ChatResponse chatResponse = chatModel.call(prompt);

            if (chatResponse.getResult() != null && chatResponse.getResult().getOutput() != null) {
                String responseContent = chatResponse.getResult().getOutput().getContent();
                System.out.println("直接请求返回内容: " + (responseContent != null ? responseContent.substring(0, Math.min(50, responseContent.length())) + "..." : "无内容"));

                // 保存到数据库
                saveTravelPlanToDatabase(tempTaskId, message, responseContent);

            } else {
                System.out.println("直接请求返回内容: 无有效响应");

                // 保存失败记录到数据库
                saveTravelPlanToDatabase(tempTaskId, message, null, "failed");
            }

            return chatResponse;
        } catch (Exception e) {
            e.printStackTrace();

            String tempTaskId = "direct-error-" + java.util.UUID.randomUUID().toString();

            ChatResponse errorResponse = new ChatResponse();
            ChatResponse.Result result = new ChatResponse.Result();
            Message errorMessage = new AssistantMessage("处理请求时发生错误: " + e.getMessage());
            result.setOutput(errorMessage);
            errorResponse.setResult(result);

            // 保存异常记录到数据库
            saveTravelPlanToDatabase(tempTaskId, chatRequest.getMessage(), null, "failed");

            return errorResponse;
        }
    }

    /**
     * 保存旅游方案到数据库
     * @param taskId 任务ID
     * @param requestPrompt 用户请求内容
     * @param aiResponse AI回复内容
     */
    private void saveTravelPlanToDatabase(String taskId, String requestPrompt, String aiResponse) {
        saveTravelPlanToDatabase(taskId, requestPrompt, aiResponse, "generated");
    }

    /**
     * 保存旅游方案到数据库（带状态）
     * @param taskId 任务ID
     * @param requestPrompt 用户请求内容
     * @param aiResponse AI回复内容
     * @param status 处理状态
     */
    private void saveTravelPlanToDatabase(String taskId, String requestPrompt, String aiResponse, String status) {
        try {
            TravelPlans travelPlan = new TravelPlans();
            travelPlan.setRequestPrompt(requestPrompt);

            // 注意：这里假设您的TravelPlans实体类中的aiResponse是String类型
            // 如果是long类型（如您之前所示），则可能需要修改TravelPlans类或进行转换
            if (aiResponse != null) {
                travelPlan.setAiResponse(aiResponse);
            }

            travelPlan.setCreatedAt(LocalDateTime.now());
            travelPlan.setStatus(status);
            travelPlan.setTaskId(taskId); // 设置任务ID

            // 保存到数据库
            travelPlansService.saveTravelPlan(travelPlan);

            System.out.println("成功保存旅游方案到数据库，ID: " + travelPlan.getPlanId() + ", TaskID: " + taskId);
        } catch (Exception e) {
            System.err.println("保存旅游方案到数据库时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}